<?php

namespace app\configure\controller;

use app\configure\model\ConfigHouseKeeperModel;
use app\configure\model\ConfigHouseModel;
use think\admin\Controller;
use think\admin\extend\DataExtend;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class HouseKeeper extends Controller
{
    /**
     * 当前操作数据库
     * @var string
     */
    private string $table = 'ConfigHouseKeeper';

    /**
     * 客服管家管理
     * @auth true
     * @menu true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index()
    {
        $this->title = '客服管家管理';
//        $this->type =$this->request->param('type', 'index');
        $this->_query(ConfigHouseKeeperModel::class)->like('name')->equal('type')->with(["House"])->order('id desc')->page(true, true);
    }

    /**
     * 添加
     * @auth true
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function add()
    {
        $this->_applyFormToken();
        $this->_form(ConfigHouseKeeperModel::class, 'form');
    }

    /**
     * 修改
     * @auth true
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function edit()
    {
        $this->_applyFormToken();
        $this->_form(ConfigHouseKeeperModel::class, 'form');
    }

    /**
     * 表单数据处理
     * @param array $data
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        if ($this->request->isGet()) {
            $data['nid'] = intval($data['unit'] ?? input('unit', '0'));
            $cates = (new ConfigHouseModel)->where(['is_deleted' => 0])->order('sort asc,id asc')->select();
            $this->cates = DataExtend::arr2table(array_merge($cates->toArray(), [['id' => '0', 'nid' => '-1', 'name' => '顶部分类']]), 'id', 'nid');
            if (isset($data['id'])) foreach ($this->cates as $cate) {
                $cate['unit'] = $cate['id'];
                if ($cate['id'] === $data['id']) $data = $cate;
                foreach ($this->cates as $key => $cate) if ((isset($data['spt']) && $data['spt'] <= $cate['spt'])) {
                    unset($this->cates[$key]);
                }
            }
            $model = new ConfigHouseKeeperModel();
            $caller = $model->where(['id' => $this->request->get('id')])->find();
            $this->caller = $caller;
        }
    }

    /**
     * 修改排序
     * @auth true
     * @throws DbException
     */
    public function sort()
    {
        $this->_save(ConfigHouseKeeperModel::class);
    }


    public function del()
    {
    }

    /**
     * 删除
     * @auth true
     * @throws DbException
     */
    public function remove()
    {
        $this->_delete(ConfigHouseKeeperModel::class);
    }
}